package org.spiderflow.core.job;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderflow.common.context.SpiderContext;
import org.spiderflow.common.model.SpiderOutput;

/**
 * @author zsh
 */
public class SpiderJobContext extends SpiderContext {

    private static final Logger logger = LoggerFactory.getLogger(SpiderJobContext.class);

    private final OutputStream outputStream;

    private final List<SpiderOutput> outputs = new ArrayList<>();

    private final boolean output;

    public SpiderJobContext(OutputStream outputStream, boolean output) {
        super();
        this.outputStream = outputStream;
        this.output = output;
    }

    public void close() {
        try {
            this.outputStream.close();
        } catch (RuntimeException | IOException e) {
            //do nothing
        }
    }

    @Override
    public void addOutput(SpiderOutput output) {
        if (this.output) {
            synchronized (this.outputs) {
                this.outputs.add(output);
            }
        }
    }

    @Override
    public List<SpiderOutput> getOutputs() {
        return outputs;
    }

    public OutputStream getOutputStream() {
        return this.outputStream;
    }

    public static SpiderJobContext create(String directory, String id, Integer taskId, boolean output) {
        OutputStream os = null;
        try {
            File file = new File(new File(directory), id + File.separator + "logs" + File.separator + taskId + ".log");
            File dirFile = file.getParentFile();
            if (dirFile.exists() || dirFile.mkdirs()) {
                os = new FileOutputStream(file, true);
            }
        } catch (Exception e) {
            logger.error("创建日志文件出错", e);
        }
        SpiderJobContext context = new SpiderJobContext(os, output);
        context.setFlowId(id);
        return context;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SpiderJobContext)) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        SpiderJobContext that = (SpiderJobContext) o;

        if (output != that.output) {
            return false;
        }
        if (!getOutputStream().equals(that.getOutputStream())) {
            return false;
        }
        return getOutputs().equals(that.getOutputs());
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + getOutputStream().hashCode();
        result = 31 * result + getOutputs().hashCode();
        result = 31 * result + (output ? 1 : 0);
        return result;
    }
}
